<template>
  <div class="chat-container">
    <el-row class="header" justify="center" align="middle">
      <el-col :span="24">
        <div class="header-content">
          <h1>欢迎来到聊天系统</h1>
        </div>
      </el-col>
    </el-row>

    <el-row class="chat-content">
      <el-col :span="6" class="user-list">
        <el-card class="user-card" shadow="hover">
          <h3>在线用户</h3>
          <el-divider></el-divider>
          <ul>
            <li v-for="user in onlineUsers" :key="user.id" class="user-item" @click="startChat(user)">
              <img class="user-avatar" :src="user.avatar" alt="avatar" />
              <div class="user-info">
                <span class="user-name">{{ user.userName }}</span>
                <span class="user-dept">{{ user.deptName }}</span>
              </div>
            </li>
          </ul>
          <h3>用户列表</h3>
          <el-divider></el-divider>
          <ul>
            <li
              v-for="user in onlineUsers"
              :key="user.id"
              class="user-item"
              @click="startChat(user)"
            >
              <img class="user-avatar" :src="user.avatar" alt="avatar" />
              <div class="user-info">
                <span class="user-name">{{ user.userName }}</span>
                <span class="user-dept">{{ user.deptName }}</span>
              </div>
            </li>
          </ul>
          <h3>用户列表</h3>
          <el-divider></el-divider>
          <ul>
            <li
              v-for="user in allUsers"
              :key="user.id"
              class="user-item"
              @click="startChat(user)"
            >
              <img class="user-avatar" :src="user.avatar" alt="avatar" />
              <div class="user-info">
                <span class="user-name">{{ user.userName }}</span>
                <span class="user-dept">{{ user.deptName }}</span>
              </div>
            </li>
          </ul>
        </el-card>
      </el-col>

      <el-col :span="18" class="chat-area">
        <el-card class="chat-card" shadow="hover">
          <div class="current-chat-user" v-if="currentChatUserName">
            <h3>正在与 {{ currentChatUserName }} 聊天</h3>
          </div>
          <div class="messages" ref="messageBox">
            <el-timeline>
              <el-timeline-item v-for="msg in messages" :key="msg.timestamp" :timestamp="msg.timestamp"
                placement="bottom">
                <div :class="[
                  'message',
                  msg.sender === getUserId()
                    ? 'message-self'
                    : 'message-other',
                ]">
                  <p>
                    <strong>{{ msg.sender }}</strong> {{ msg.content }}
                  </p>
                  <span class="timestamp">{{ msg.timestamp }}</span>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>

          <div class="input-area">
            <el-input v-model="newMessage" type="textarea" placeholder="输入消息" @keyup.enter.native="sendMessage" rows="3"
              resize="none" />
            <el-button class="send-button" type="primary" @click="sendMessage">发送</el-button>
            <el-button class="emoji-button" type="default" @click="toggleEmojiPicker">😊</el-button>
            <el-button class="file-button" type="default" @click="openFileDialog">📁</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog title="选择文件" :visible.sync="fileDialogVisible">
      <el-upload class="upload-demo" drag action="/upload" :on-success="handleUploadSuccess"
        :on-error="handleUploadError" :before-upload="beforeUpload">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或<span class="upload-demo__link">点击上传</span>
        </div>
        <div class="file-preview" v-if="filePreview">
          已选择文件：{{ filePreview }}
        </div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { list, getAuthRole, listUser } from "@/api/monitor/online";

export default {
  data() {
    return {
      onlineUsers: [], // 在线用户列表
      allUsers: [], // 所有用户列表
      messages: [], // 聊天消息列表
      newMessage: "", // 新消息输入框内容
      currentChatUser: null, // 当前聊天的用户
      currentChatUserName: "", // 当前聊天的用户名
      websocket: null, // WebSocket 实例
      fileDialogVisible: false, // 文件上传对话框显示状态
      filePreview: "", // 文件预览文本
      currentUserRole: "", // 当前用户角色
    };
  },
  created() {
    this.getAuthRole(); // 获取当前用户角色
    this.connectWebSocket();
    this.getOnlineUsers(); // 获取在线用户列表
    this.getAllUsers(); // 获取所有用户列表
  },
  beforeDestroy() {
    this.closeWebSocket();
  },
  methods: {
    async getAllUsers() {
      try {
        const response = await listUser(); // 获取所有用户列表
        if (response.code === 200) {
          this.allUsers = response.rows; // 假设返回的数据结构为 { rows: [] }
        } else {
          this.$message.error("获取用户列表失败: " + response.msg);
        }
      } catch (error) {
        console.error("获取用户列表失败:", error);
      }
    },

    async getAuthRole() {
      const userId = this.getUserId();
      // console.log("获取角色时的用户 ID:", userId); // 打印获取到的 userId

      try {
        const response = await getAuthRole(userId);
        if (response.code === 200) {
          // 假设 response.roles 是一个数组，里面包含角色信息
          const roles = response.roles;
          this.currentUserRole = roles.find((role) => role.admin).roleName;
          console.log("当前用户角色:", this.currentUserRole);
        } else {
          console.error("获取用户角色失败:", response.msg);
        }
      } catch (error) {
        console.error("获取用户角色失败:", error);
      }
    },

    async getOnlineUsers() {
      try {
        const response = await list(); // 获取在线用户列表
        const users = response.rows; // 假设返回数据结构为 { rows: [] }

        // 处理用户列表
        const usersWithRoles = users.map((user) => {
          // 根据其他数据来处理用户，或者将用户标记为没有角色信息
          user.role = {}; // 设置默认角色信息或空角色信息
          return user;
        });

        this.onlineUsers = usersWithRoles; // 更新在线用户列表
      } catch (error) {
        console.error("获取在线用户失败:", error);
      }
    },

    startChat(user) {
      console.log("聊天用户信息:", user);
      if (
        this.currentUserRole === "普通角色" &&
        user.role.roleName !== "超级管理员"
      ) {
        this.$message.error("普通角色只能与超级管理员聊天！");
        return;
      }

      this.currentChatUser = user; // 设置当前聊天的用户
      this.currentChatUserName = user.userName; // 设置当前聊天用户名
      this.messages = []; // 清空聊天记录
      this.connectWebSocket(); // 重新连接 WebSocket，以便与当前用户聊天
    },

    connectWebSocket() {
      const userId = this.getUserId();
      const receiverId = this.currentChatUser
        ? this.currentChatUser.userId
        : null;

      if (this.websocket && this.websocket.readyState !== WebSocket.CLOSED) {
        this.websocket.close(); // 关闭旧的 WebSocket 连接
      }

      const url = receiverId
        ? `ws://localhost:8080/websocket/message?userId=${userId}&receiverId=${receiverId}`
        : `ws://localhost:8080/websocket/message?userId=${userId}`;

      this.websocket = new WebSocket(url);

      this.websocket.onopen = () => {
        console.log("WebSocket 连接已打开");
      };

      this.websocket.onmessage = (event) => {
        const message = JSON.parse(event.data);
        this.messages.push({
          sender: message.senderId,
          content: message.content,
          timestamp: message.timestamp,
        });
        this.$nextTick(() => {
          this.$refs.messageBox.scrollTop = this.$refs.messageBox.scrollHeight;
        });
      };

      this.websocket.onclose = () => {
        console.log("WebSocket 连接已关闭");
      };

      this.websocket.onerror = (error) => {
        console.error("WebSocket 连接错误:", error);
      };
    },

    closeWebSocket() {
      if (this.websocket) {
        this.websocket.close();
      }
    },

    getUserId() {
      const userId = this.$store.state.user.id;
      // console.log("用户 ID:", userId); // 打印用户 ID
      return Number(userId); // 确保返回的是数字
    },

    sendMessage() {
      if (
        this.newMessage.trim() !== "" &&
        this.websocket.readyState === WebSocket.OPEN
      ) {
        const message = {
          senderId: this.getUserId(),
          content: this.newMessage,
          receiverId: this.getSuperAdminId(), // 确保这个方法存在
          timestamp: new Date().toLocaleString(),
        };
        this.websocket.send(JSON.stringify(message)); // 确保发送的是 JSON 字符串
        this.newMessage = "";
      } else {
        console.warn("WebSocket 未连接或消息为空，无法发送");
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const messageBox = this.$refs.messageBox;
        messageBox.scrollTop = messageBox.scrollHeight;
      });
    },
    formatMessage(me) {
      if (msg.type === "system") {
        return `系统提醒：${msg.content}`;
      }
      return `${msg.sender}: ${msg.content}`;
    },

    toggleEmojiPicker() {
      // 显示或隐藏表情选择器
    },

    openFileDialog() {
      this.fileDialogVisible = true;
    },

    handleUploadSuccess(response, file, fileList) {
      console.log("文件上传成功:", response);
      // 处理上传成功后的逻辑
    },

    handleUploadError(error, file, fileList) {
      console.error("文件上传失败:", error);
    },
    beforeUpload(file) {
      const isFileTypeValid = [
        "image/jpeg",
        "image/png",
        "application/pdf",
      ].includes(file.type);
      if (!isFileTypeValid) {
        this.$message.error("只能上传 JPG/PNG/PDF 文件");
      }
      return isFileTypeValid;
    },
  },
};
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #e2e2e2 0%, #ffffff 100%);
  color: #333;
}

.header {
  background: linear-gradient(135deg, #4a90e2, #50e3c2);
  color: #fff;
  padding: 20px;
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  border-bottom: 2px solid #dcdfe6;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.chat-content {
  flex: 1;
  display: flex;
  padding: 20px;
}

.user-list {
  border-right: 2px solid #e1e4e8;
  background-color: #f5f6f9;
  padding: 10px;
}

.user-card {
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.user-card ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.user-item {
  padding: 12px;
  font-weight: 500;
  border-bottom: 1px solid #e1e4e8;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  background-color: #ccc;
}

.user-name {
  font-size: 16px;
  color: #333;
}

.chat-area {
  display: flex;
  flex-direction: column;
  padding-left: 20px;
}

.chat-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.messages {
  flex: 1;
  overflow-y: auto;
  height: 550px;
  padding: 15px;
  background-color: #ffffff;
  border: 1px solid #e1e4e8;
  border-radius: 8px;
  margin-top: 60px; /* 给消息列表留出上方标题的空间 */
}

.message {
  padding: 10px;
  border-radius: 12px;
  margin-bottom: 10px;
  max-width: 75%;
  word-break: break-word;
  background-color: #f5f5f5;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  margin: 8px 0;
  border-radius: 8px;
}

.message-self {
  background-color: #e1f5fe;
  align-self: flex-end;
  color: #fff;
  float: right;
}

.message-other {
  background-color: #ffffff;
  align-self: flex-start;
  border: 1px solid #e1e4e8;
  float: left;
}

.timestamp {
  display: block;
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.input-area {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f5f5f5;
}

.send-button {
  margin-left: 10px;
}

.emoji-button,
.file-button {
  margin-left: 10px;
}

.file-preview {
  margin-top: 10px;
}

.current-chat-user {
  text-align: center;
  padding: 10px;
  background-color: #f0f0f0;
  border-bottom: 1px solid #e1e4e8;
  margin-bottom: 10px;
  position: absolute;
  top: 0;
  width: 100%;
  z-index: 1;
}
</style>